The Repository pattern.
Repositories are classes or components that encapsulate the logic required to access data sources.
They centralize common data access functionality, providing better maintainability and decoupling the infrastructure or technology used to access databases from the domain model layer.
The basic difference between model and Repository are
Models allow you to query for data in your tables, as well as insert new records into the table. What this is saying, is a Model opens access to a database table. It also allows you to relate to other models to pull out data without having to write individual queries.
A repository allows you to handle a Model without having to write massive queries inside of a controller. In turn, keeping the code tidier, modular and easier to debug should any errors arise.
Example
You could use a repository in the following way:
public function makeNotification($class, $title, $message)
{
$notification = new Notifications;
...
$notification->save();
return $notification->id;
}
public function notifyAdmin($class, $title, $message)
{
$notification_id = $this->makeNotification($class, $title, $message);
$users_roles = RolesToUsers::where('role_id', 1)->orWhere('role_id', 2)->get();
$ids = $users_roles->pluck('user_id')->all();
$ids = array_unique($ids);
foreach($ids as $id) {
UserNotifications::create([
'user_id' => $id,
'notification_id' => $notification_id,
'read_status' => 0
]);
}
}
controller:
protected $notification;
public function __construct(NotificationRepository $notification)
{
$this->notification = $notification;
}
public function doAction()
{
...
$this->notification->notifyAdmin('success', 'User Added', 'A new user joined the system');
...
}
The repository pattern consists of adding an abstraction layer between the data access layer and the business logic layer of an application that are in charge of accessing the data source and obtaining the different data models. It is a data access pattern that prompts a more loosely coupled approach to data access
We are Recommending you:
- Laravel 8 .htaccess file for php 8
- Laravel's .htaccess to remove "public" from URL
- Laravel 7 multi auth login
- How to change timezone in laravel 8
- How to create real time sitemap.xml file in Laravel
- Integrate Zoho SMTP Mail Configurations in Laravel?
- Laravel 8/7 Overwriting the Default Pagination System
- Custom 404 Page In Laravel 8
- Laravel remove public from url
Step Out of Your Comfort Zone: 10 Powerful...
Is Mobile Reels Harming Our Children? Here's...
Simple body language tricks1. Stand with...
Best Free Websites to Learn CodingIf you...
Is Mobile Reels Harming Our Children? Here's...
There are two types of pagination methods...
How to create real time sitemap.xml file...
Learning to code is fun, but beginners often...